package com.qm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qm.anno.CacheFind;
import com.qm.mapper.ItemCatMapper;
import com.qm.pojo.ItemCat;
import com.qm.service.ItemCatService;
import com.qm.util.ObjectMapperUtil;
import com.qm.vo.LayUITree;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;

/**
 @author james
 @create 2021-03-11 20:33
 */
@Service
public class ItemCatServiceImpl implements ItemCatService {

    @Autowired
    private ItemCatMapper itemCatMapper;

    //Spring容器初始化时，该注解不是必须注入。但是如果程序调用则必须有值。
    @Autowired(required = false)
    private Jedis jedis;

    @Override
    @CacheFind(key = "ITEM_CAT_ID")
    public ItemCat findItemCatById(Long id) {
        return itemCatMapper.selectById(id);
    }

    @Override
    @CacheFind(key = "ITEM_CAT_LIST")
    public List<LayUITree> findItemCatList() {
        List<LayUITree> itemCatList = itemCatMapper.findItemCatList();
        return itemCatList;
    }

    @Override
    public List<LayUITree> findItemCatByCache() {
        long startTime = System.currentTimeMillis();
        List<LayUITree> treList = new ArrayList<>();
        //1.定义key
        String key = "ITEM_CAT";
        //2.判断数据是否存在
        if (jedis.exists(key)) {
            String json = jedis.get(key);
            treList = ObjectMapperUtil.toObject(json, treList.getClass());
            long endTime = System.currentTimeMillis();
            System.out.println("redis查询！耗时：" + (endTime-startTime));
        } else {
            treList = findItemCatList();
            String json = ObjectMapperUtil.toJSON(treList);
            jedis.set(key, json);
            long endTime = System.currentTimeMillis();
            System.out.println("查询数据库！ 耗时：" + (endTime-startTime));
        }
        return treList;
    }
}
